package com.ychs.lawyerback01.service.imp;

import com.ychs.lawyerback01.mapper.DocumentMapper;
import com.ychs.lawyerback01.pojo.UploadEntity;
import com.ychs.lawyerback01.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
public class DocumentServiceImp implements DocumentService {
    @Autowired
    private DocumentMapper documentMapper;

    @Value("${file.upload.location}")
    private String uploadLocation;

    @Override
    public UploadEntity uploadDocument(MultipartFile file, String seekerName) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        if (!Arrays.asList("docx", "pdf").contains(fileExtension)) {
            throw new IllegalArgumentException("只支持docx和pdf文件");
        }

        Path uploadPath = Paths.get(uploadLocation);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        String storedFilename = UUID.randomUUID() + "." + fileExtension;
        Path filePath = uploadPath.resolve(storedFilename);
        Files.copy(file.getInputStream(), filePath);

        UploadEntity uploadEntity = new UploadEntity();
        uploadEntity.setSeekerName(seekerName);
        uploadEntity.setUploadTime(new Date());
        uploadEntity.setFileName(originalFilename);
        uploadEntity.setFilePath(filePath.toString());
        uploadEntity.setFileType(fileExtension);
        uploadEntity.setFileSize(file.getSize());
        uploadEntity.setStatus("pending");

        documentMapper.insert(uploadEntity);
        return uploadEntity;
    }

    @Override
    public List<UploadEntity> getPendingDocuments(String fileName, String seekerName, String status) {
        Map<String, Object> params = new HashMap<>();
        params.put("fileName", fileName);
        params.put("seekerName", seekerName);
        params.put("status", status != null ? status : "pending");
        return documentMapper.selectByCondition(params);
    }

    @Override
    public List<UploadEntity> getPendingDocuments() {
        return documentMapper.selectByStatus("pending");
    }

    @Override
    public UploadEntity approveDocument(Long id, String approvalBy) {
        UploadEntity uploadEntity = documentMapper.selectById(id);
        if (uploadEntity == null) {
            throw new RuntimeException("文档不存在");
        }
        uploadEntity.setStatus("approved");
        uploadEntity.setApprovalBy(approvalBy);
        uploadEntity.setApprovalTime(new Date());
        documentMapper.updateStatus(uploadEntity);
        return uploadEntity;
    }

    @Override
    public UploadEntity rejectDocument(Long id, String approvalBy, String comments) {
        UploadEntity uploadEntity = documentMapper.selectById(id);
        if (uploadEntity == null) {
            throw new RuntimeException("文档不存在");
        }
        uploadEntity.setStatus("rejected");
        uploadEntity.setApprovalBy(approvalBy);
        uploadEntity.setApprovalTime(new Date());
        uploadEntity.setComments(comments);
        documentMapper.updateStatus(uploadEntity);
        return uploadEntity;
    }

    @Override
    public UploadEntity getDocument(Long id) {
        return documentMapper.selectById(id);
    }

    @Override
    public Map<String, Object> getDocumentsByPage(int page, int pageSize, String fileName, String seekerName, String status) {
        int offset = (page - 1) * pageSize;
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        params.put("fileName", fileName);
        params.put("seekerName", seekerName);
        params.put("status", status);

        List<UploadEntity> documents = documentMapper.selectByCondition(params);
        long total = documentMapper.countByCondition(params);

        Map<String, Object> result = new HashMap<>();
        result.put("list", documents);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (int) Math.ceil((double) total / pageSize));

        return result;
    }

    @Override
    public Page<UploadEntity> getPendingDocuments(int page, int pageSize, String fileName, String seekerName, String status) {
        int offset = (page - 1) * pageSize;
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        params.put("fileName", fileName);
        params.put("seekerName", seekerName);
        params.put("status", status);

        List<UploadEntity> documents = documentMapper.selectByCondition(params);
        long total = documentMapper.countByCondition(params);

        return new PageImpl<>(documents, PageRequest.of(page - 1, pageSize), total);
    }

}